import os
from datetime import datetime
from typing import List

import allure
from selenium.common import NoSuchElementException
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.wait import WebDriverWait

from src.day42.utils import root_dir
from src.day42.utils.black_handle import black_wrapper
from src.day42.utils.log_util import logger


class Base:
    DEFAULT_IMPLICITLY = 10
    def __init__(self,driver:WebDriver = None):
            self.driver=driver

    @black_wrapper
    def find(self, by, value) -> WebElement:
        if isinstance(by, tuple):
            logger.debug(f"使用 {by[0]} 的定位方式,进行元素 {by[1]} 的定位")
            ele = self.driver.find_element(*by)
        else:
            logger.debug(f"使用 {by} 的定位方式,进行元素 {value} 的定位")
            ele = self.driver.find_element(by, value)
        return ele

    def get_time_name(self, dir_name, file_name):
        dir_path = f"{root_dir}/data/{dir_name}"
        os.makedirs(dir_path, exist_ok=True)
        return f'{dir_path}/{file_name}'

    def save_page_source(self):
        # 获取当前时间
        now = datetime.now()
        # 格式化时间，包含毫秒
        time_format = now.strftime('%m-%d-%H-%M-%S-%f')[:-3]
        html_data = self.driver.page_source
        path = self.get_time_name('page_source', f'PageSource{time_format}.html')
        with open(path, "w", encoding="utf-8") as f:
            f.write(html_data)
        allure.attach.file(path, attachment_type=allure.attachment_type.HTML)

    def save_screen_shot(self):
        # 获取当前时间
        now = datetime.now()
        # 格式化时间，包含毫秒
        time_format = now.strftime('%m-%d-%H-%M-%S-%f')[:-3]
        path = self.get_time_name('screen_shot', f'img{time_format}.png')
        self.driver.save_screenshot(path)
        allure.attach.file(path, attachment_type=allure.attachment_type.PNG)

    @black_wrapper
    def finds(self, by, value=None) -> List[WebElement]:
        if isinstance(by, tuple):
            logger.debug(f"使用 {by[0]} 的定位方式,进行元素 {by[1]} 的定位")
            eles = self.driver.find_elements(*by)
        else:
            logger.debug(f"使用 {by} 的定位方式,进行元素 {value} 的定位")
            eles = self.driver.find_elements(by, value)
        return eles

    def find_and_click(self, by, value=None):
        """
        查找并点击
        :param by:
        :param value:
        :return:
        """
        ele = self.find(by=by, value=value)
        ele.click()

    def find_and_send(self, by, value=None, text=None):
        """
        查找并输入
        :param by:
        :param value:
        :param text:
        :return:
        """
        ele = self.find(by=by, value=value)
        logger.debug(f"进行信息{text}的输入操作")
        ele.send_keys(text)

    def wait(self, method, time_out=5):
        el = WebDriverWait(self.driver, time_out).until(method)
        return el

    def set_implicitly_wait(self, times=1):
        self.driver.implicitly_wait(times)

    def my_swip(self, duration=2000, count=1):
        size = self.driver.get_window_size()
        height = size.get('height')
        weight = size.get('width')
        start_x = weight * 0.5
        start_y = height * 0.8
        end_x = weight * 0.5
        end_y = height * 0.2
        counts = 0
        while counts <= count:
            self.driver.swipe(start_x, start_y, end_x, end_y, duration)
            counts += 1

    def swip_find(self, by, value, max_count=5, duration=None):
        count = 0
        while count < max_count:
            try:
                el = self.find(by, value)
                self.set_implicitly_wait(self.DEFAULT_IMPLICITLY)
                return el
            except Exception as e:
                self.set_implicitly_wait()
                self.my_swip(duration)
                count += 1
        raise NoSuchElementException
